package com.bz.redis.service.impl;

import com.bz.redis.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private String order_item_id_key = "order:item:id:key";

    private Long init_item_id = 2000L;

    /**
     * 生成订单ID
     * @return
     */
    @Override
    public Long selectOrderId() {
        //查询redis中的订单Id
        Integer value = (Integer) redisTemplate.opsForValue().get(order_item_id_key);
        //如果订单ID的值不存在，将默认值set到redis中
        if (value == null || value == 0){
            redisTemplate.opsForValue().set(order_item_id_key,init_item_id);
        }
        //通过redis中的自增长将默认值做递增处理。
        Long orderId = redisTemplate.opsForValue().increment(order_item_id_key);
        return orderId;
    }
}
